package com.bimowu.first.controller;

import com.bimowu.first.model.Product;
import com.bimowu.first.service.ProductService;
import com.bimowu.first.utils.bean.CommonQueryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping(value = "/productview")
public class ProductViewController {
    @Autowired
    ProductService productService;


    @RequestMapping("/listProduct")
    public String listProduct(@RequestParam(value = "name",defaultValue = "")String name,
                              Model model,
                              @RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                              @RequestParam(value = "pageSize",defaultValue = "4")int pageSize){
        Product record =new Product();
        record.setName(name);

        model.addAttribute("name",name);
        long total =productService.count(record);
        int totalPageNum = (int )total / pageSize;
        if(total % pageSize > 0){
            totalPageNum +=1;
        }
        CommonQueryBean query =new CommonQueryBean();
        query.setPageSize(pageSize);
        query.setPageNum(pageNum);
        query.setStart((pageNum-1)*pageSize);


        List<Product>list = productService.list4Page(record,query);

        model.addAttribute("total",total);
        model.addAttribute("list",list);
        model.addAttribute("totalPage",totalPageNum);
        model.addAttribute("pageNum",pageNum);
        model.addAttribute("pageSize",pageSize);

        return "index";

    }
    @RequestMapping("/add")
    public String add() {
        return "add";
    }
    @RequestMapping("/addProduct")
    public String addProduct(Product product, Model model){
        productService.save(product);
        return "redirect:listProduct";
    }
    @RequestMapping("/update")
    public String update(long id,Model model) {
        Product product = productService.selectByPrimaryKey(id);
        model.addAttribute("product",product);
        return "update";
    }
    @RequestMapping("/updateProduct")
    public String updateProduct(Product product, Model model){
        productService.updateItem  (product);
        return "redirect:listProduct";
    }
    @RequestMapping("/delete")
    public String delete(Long id) throws Exception {
        productService.deleteByPrimaryKey(id);
        return "redirect:listProduct";
    }
    @RequestMapping("/getProduct")
    public String getProduct(Long id, Model model) throws Exception {
        Product product = productService.selectByPrimaryKey(id);
        model.addAttribute("product", product);
        return "productShow";
    }

}
